// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "core/operation/concat.h"
#include "core/hal/types.h"
#include "utility/debug.h"
#include "utility/logging.h"
#include "utility/modeling.h"
#include "utility/utility.h"

namespace nnadapter {
namespace operation {

int PrepareConcat(hal::Operation* operation) {
  CONCAT_OPERATION_EXTRACT_INPUTS_OUTPUTS

  // Infer the shape and type of output operands
  CopyOperandTypeExceptQuantParams(&output_operand->type,
                                   input_operands[0]->type);

  auto infer_output_shape = [&](int32_t* input_dimensions,
                                int32_t* output_dimensions,
                                const uint32_t input_dimension_count) {
    NNADAPTER_CHECK_EQ(input_dimension_count,
                       output_operand->type.dimensions.count);
    for (uint32_t i = 0; i < input_dimension_count; i++) {
      if (output_dimensions[i] == NNADAPTER_UNKNOWN ||
          input_dimensions[i] == NNADAPTER_UNKNOWN) {
        output_dimensions[i] = NNADAPTER_UNKNOWN;
        continue;
      }
      if (i == axis) {
        output_dimensions[i] += input_dimensions[i];
      } else {
        NNADAPTER_CHECK_EQ(output_dimensions[i], input_dimensions[i]);
      }
    }
  };

  for (size_t i = 1; i < input_count - 1; i++) {
    infer_output_shape(input_operands[i]->type.dimensions.data,
                       output_operand->type.dimensions.data,
                       input_operands[i]->type.dimensions.count);
  }
  for (uint32_t i = 0; i < output_operand->type.dimensions.dynamic_count; i++) {
    for (size_t j = 1; j < input_count - 1; j++) {
      infer_output_shape(input_operands[j]->type.dimensions.dynamic_data[i],
                         output_operand->type.dimensions.dynamic_data[i],
                         input_operands[j]->type.dimensions.count);
    }
  }

  NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
  return NNADAPTER_NO_ERROR;
}

}  // namespace operation
}  // namespace nnadapter
